import gradio as gr
import os
from  .batch_universal_to_markdown import BatchUniversalToMarkdownProcessor
#from document2llm.md.batch_universal_to_markdown import BatchUniversalToMarkdownProcessor
# 从环境变量获取端口，如果没有设置，则使用默认值 34923
DEFAULT_PORT = int(os.environ.get('GRADIO_SERVER_PORT', 34923 ))

examples = [
    ["/Users/Shared/work_cache/input_cache/", "/Users/Shared/work_cache/output_cache"],
    ["~/Downloads/1-dev/input/", "~/Downloads/1-dev/output/"],
    ["~/Documents/input_docs/", "~/Documents/output_md/"],
    ["path/to/input_folder", "path/to/output_folder"],
]

home = os.path.expanduser("~")

def get_default_output_folder():
    """返回默认输出文件夹路径"""
    return os.path.join(home, "Downloads", "output_md")

def process_files(input_folder, output_folder):
    """处理文档转换"""
    # 确保输入文件夹有效
    if not input_folder.strip():
        return "请选择输入文件夹"

    # 展开用户目录中的 `~`
    input_folder = input_folder.replace('~', home).strip()

    # 确保输出文件夹有效
    if not output_folder.strip():
        output_folder = get_default_output_folder()

    output_folder = output_folder.replace('~', home).strip()

    # 创建批量处理器
    batch_processor = BatchUniversalToMarkdownProcessor(input_folder, output_folder)

    try:
        # 执行批量转换
        batch_processor.process()
        return f"处理完成。输出目录: {output_folder}"
    except Exception as e:
        return f"发生错误: {str(e)}"

# 创建 Gradio 界面
with gr.Blocks() as iface:
    gr.Markdown("# 批量文档转Markdown工具")
    gr.Markdown("将多个文档（支持 .docx, .pptx, .pdf, .html）批量转换为 Markdown 格式。")

    # 输入输出路径
    with gr.Row():
        input_folder = gr.Textbox(label="输入文件夹路径", placeholder="选择包含文档的文件夹路径")
        output_folder = gr.Textbox(label="输出文件夹路径", placeholder=f"默认: {get_default_output_folder()}")

    # 处理按钮和结果显示
    process_button = gr.Button("开始处理")
    result = gr.Textbox(label="处理结果", interactive=False)

    # 处理按钮点击事件
    process_button.click(
        fn=process_files,
        inputs=[input_folder, output_folder],
        outputs=result
    )

    # 示例展示
    gr.Markdown("## 使用示例")
    gr.Examples(
        examples=examples,
        inputs=[input_folder, output_folder],
    )

# 运行 Gradio 应用
if __name__ == "__main__":
    import argparse

    # 解析命令行参数
    parser = argparse.ArgumentParser(description="Batch Document to Markdown Converter")
    parser.add_argument("--port", type=int, default=DEFAULT_PORT, help="Port to run the Gradio app on")
    args = parser.parse_args()

    # 启动 Gradio 应用
    print(f"Starting Gradio app on port {args.port}")
    iface.launch(server_name="0.0.0.0", server_port=args.port)
"""
使用示例：
python3 -m document2llm.md.batch_universal_to_markdown -i input_documents -o output_markdown


python3 -m document2llm.md.batch_universal_to_markdown -i test-input-folder  -o output_markdown_folder

或者在Python代码中：

from document2llm.md.batch_universal_to_markdown import BatchUniversalToMarkdownProcessor

batch_processor = BatchUniversalToMarkdownProcessor("input_documents", "output_markdown")
batch_processor.process()
"""


#
